package com.hanhai.zrb.api.mongodb;

import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.mongodb.DB;
import com.mongodb.Mongo;

public class MongoUtil {
	public static final int DEFAULT_PORT = 27017;
	public static final String DEFAULT_HOST = "172.17.100.150";

	public static Logger log = Logger.getLogger(MongoUtil.class);
	
	private static Mongo instance;

	//@Resource(name="mongodbConfig")
	//private static MongodbConfig mongodbConfig;
	//没有直接注入
	private static MongodbConfig config = null;
	
	public static Mongo mongo() {
		//使用工具方法获得容器中的对象
		Object object=SpringContextUtil.getBean("mongodbConfig");
		
		if(object instanceof MongodbConfig){
			config = (MongodbConfig)object;
		}else{
			log.error("Mongodb config error~");
		}
		try {
			if (instance == null) {
				instance = new Mongo(config.getHost(), Integer.parseInt(config.getPort()));
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return instance;
	}

	public static DB db(){
		Mongo mongo = MongoUtil.mongo();
		DB db = mongo.getDB(config.getDb());
		if(db == null){
			throw new RuntimeException("Mongo db is null");
		}
		return db;
	}
	
	public static void close() {
		if (instance != null) {
			instance.close();
		}
	}

}